package com.msg.service.protocol;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.msg.model.MsgPush;
import com.msg.service.LoginService;
import com.msg.thread.GroupPushThread;
import com.msg.utils.MsgSrvUtils;
import com.pjc.annotation.Protocol;
import com.pjc.annotation.SrvToSrv;
import com.pjc.config.BaseEnums;
import com.pjc.config.GlobalKey;
import com.pjc.config.RpcReturnCode;

/**
 * 逻辑服务器与消息服务器(logic>msgSrv)
 * 
 * @author 王畅
 * @since 2015年6月21日
 */
@SrvToSrv
public class LogicToAccessHandler {

	protected static final Logger LOG = LoggerFactory.getLogger(LogicToAccessHandler.class);

	/**
	 * 推送系统消息
	 * 
	 * @author 王畅
	 * @param data
	 * @return
	 * @throws Exception
	 */
	@Protocol(protoId = GlobalKey.LogicToAccess.TRANS_SYS_MSG)
	public static int handlerSysMsg(String data) throws Exception {
		if (data == null)
			return RpcReturnCode.OK;
		JSONObject msg = JSONObject.parseObject(data);
		if (msg.getIntValue("type") != BaseEnums.NoticeTypeEnum.Notice_FlowData.getId()) {
			String toUserId = msg.getString("toUserId");
			IoSession session = MsgSrvUtils.getSession(toUserId, msg.getString("appId"));
			return writeMsg(msg.getString("appId"), toUserId, session, msg);
		}
		/*************** 滚动消息特殊处理 ********************************/
		MsgPush pushMsg = new MsgPush();
		pushMsg.setAppId(msg.getString("appId"));
		pushMsg.setData(msg.getJSONObject("data"));
		GroupPushThread.getInstance().addPushMsg(pushMsg);
		return RpcReturnCode.OK;
	}

	/**
	 * 消息服务器踢人
	 * 
	 * @author 王畅
	 * @param data
	 * @return
	 * @throws Exception
	 */
	@Protocol(protoId = GlobalKey.LogicToAccess.KICK_USER)
	public static int handlerKickUser(String data) throws Exception {
		JSONObject json = JSONObject.parseObject(data);
		LoginService.kickUserHandler(json.getString("userId"), json.getString("appId").toLowerCase());
		return RpcReturnCode.OK;
	}

	/**
	 * 发送信息
	 * 
	 * @param appID
	 * @param toUserID
	 * @param session
	 * @param msg
	 * @return
	 * @throws Exception
	 */
	private static int writeMsg(String appId, String toUserId, IoSession session, JSONObject msg) throws Exception {
		if (session == null) {
			return RpcReturnCode.USER_OFFLINE;
		}
		long currentTimeMillis = System.currentTimeMillis();
		if (session.isClosing()) {
			LoginService.userLogout(appId, session, toUserId, currentTimeMillis);
			return RpcReturnCode.USER_OFFLINE;
		}
		boolean isDone = MsgSrvUtils.write(session, msg);
		if (!isDone) {
			LoginService.userLogout(appId, session, toUserId, currentTimeMillis);
			return RpcReturnCode.USER_OFFLINE;
		}
		return RpcReturnCode.OK;
	}
}
